package net.zkbc.helloworld.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import net.zkbc.helloworld.entity.User;
import net.zkbc.helloworld.service.UserService;

@Controller
public class HomeController {

	private static final Logger LOG = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	private UserService userService;

	@RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginForm() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		LOG.info("username={}", username);

		User loginUser = userService.findUserByLoginName(username);
		if (loginUser == null) {
			redirectAttributes.addFlashAttribute("error", "用户不存在");
			return "redirect:/login";
		}

		request.getSession().setAttribute("loginUser", loginUser);
		return "redirect:/";
	}
}
